#include <stdio.h>      /* NULL */

#include "debug.h"
#include "globals.h"    /* ADDR_MEM_PHYSICAL, ADDR_MEM_GPIO */
#include "lcd_state.h"
#include "memory.h"
#include "state_loop.h"

int main(int argc, char ** argv)
{
    memaddr_t * base_address = NULL;
    memaddr_t * gpio_base_address = NULL;
    int retval = 0;
    
    memaddr_t * vga_port = NULL;
    
    /* Set up physical to virtual memory remapping */
    base_address = remap_memory(ADDR_MEM_PHYSICAL);
    if (base_address == NULL)
    {
        debug_out("Remap of memory resulted in NULL address\r\n");
        return RETURN_MEMORY_MAP_FAILED;
    }
    else
    {
        /* Map IO registers to memory addresses */
        if (map_memory_register(vga_port) == NULL)
        {
            /* Map failed - current address is NULL */
            debug_out("Mapping of pointer to invalid address\r\n");
            return RETURN_MEMORY_MAP_FAILED;
        }
    }
    
    /* Set up GPIO memory - this will reset map_memory_register() */
    gpio_base_address = remap_memory(ADDR_MEM_GPIO);
    if (gpio_base_address == NULL)
    {
        debug_out("Remap of memory resulted in NULL address\r\n");
        return RETURN_MEMORY_MAP_FAILED;
    }
    else
    {
        /* Initialise the LCD screen */
        retval = init_lcd_screen(gpio_base_address);
        if (retval < 0)
        {
            return RETURN_COMPONENT_INIT_ERROR;
        }
    }
    
    retval = run_state_loop();
    if (retval < 0)
    {
        /* Handle error report */
    }
    
    return RETURN_OK;
}
